import {Dispatch,  useEffect, useState} from "react";
import {getScene, updateScene} from "../services";
import type { IScene } from "../services";
import {IComponent, IComponentType} from "@bastet/widgets";
import {message} from "antd";
import {resizeCustom, testSceneWidthLocalWidget} from "./useWidget.ts";


type IGetMaterial = (value: any, debug?: boolean) => any;
export function useScene ():[ IScene| undefined, IGetMaterial, IGetMaterial] {
  const [ scene, setScene ] = useState<IScene>()

  const getSceneById = (id: string, debug?: boolean) => {
    return getScene(id).then(async ({ code, data }) => {
      /**
       * 请求下来的 widget
       */
      if (code === 200 && data) {
        // console.log('getSceneById: => ', data)
        if (data.widgets?.length) {
          // console.log('getSceneById: => ', data.widgets)
          data.widgets = data.widgets.map(resizeCustom)
          if (debug) {
            data.widgets = await testSceneWidthLocalWidget(data.widgets)
          }
        }
        setScene(data)
        return data
      }
    })
  }

  const onUpdateScene = (widgets: IComponent[])=> {
    if (scene) {
      return updateScene({ ...scene, widgets }).then(({ code, data, msg }) => {
        if (code === 200) {
          message.info(msg)
          setScene(data)
          return data
        }
      })
    }
  }

  return [ scene, getSceneById, onUpdateScene ]
}
